﻿#include<iostream>
#include<stdexcept>

class MyList {
private:
	//堆分配，以便于扩容
	int* arr;
	int arrCapacity = 10;
	int arrSize = 0;
	int extendRatio = 2;

public:
	MyList() {
		arr = new int[arrCapacity];
	}
	~MyList() {
		delete[] arr;
	}
	//数组当前有效元素数量
	int GetSize() {
		return arrSize;
	}
	//数组最大空间
	int GetCapacity() {
		return arrCapacity;
	}
	int Get(int index) {
		if (index < 0 || index > GetSize())
			throw std::out_of_range("index overflow");
		return arr[index];
	}
	void Set(int index, int val) {
		if (index<0 || index>GetSize())
			throw std::out_of_range("index overflow");
		arr[index] = val;
	}
	void AddLast(int num) {
		arr[GetSize()] = num;
		arrSize++;
	}
	void Add(int num, int index) {
		if (index<0 || index>GetSize())
			throw std::out_of_range("index overflow");
		if (GetSize() == GetCapacity())
			ExtendCapacity();
		//从后向前，每个元素后移一位
		for (int j = GetSize() - 1; j >= index; j--)
			arr[j + 1] = arr[j];
		arr[index] = num;
		arrSize++;
	}

	int Delete(int index) {
		if (index<0 || index>GetSize())
			throw std::out_of_range("index overflow");
		int delVal = arr[index];
		for (int j = index; j < GetSize(); j++)
			arr[j] = arr[j + 1];
		arrSize--;
		return delVal;
	}

	void ExtendCapacity() {
		int newCapacity = GetCapacity() * extendRatio;
		int* old = arr;
		arr = new int[newCapacity];
		//存放原来的元素到新数组
		for (int i = 0; i < GetSize(); i++) {
			arr[i] = old[i];
		}
		delete[] old;
		arrCapacity = newCapacity;
	}

};


int main() {

	try {
		std::cout << "throw runtime error" << std::endl;
		throw std::invalid_argument("runtime error");
	}
	catch (std::out_of_range error) {
		std::cout << "catch and deal out_of_range error" << std::endl;
	}
	catch (std::runtime_error error) {
		std::cout << "catch and deal runtime_error error" << std::endl;
	}
	catch (...) {
		std::cout << "catch unknown error" << std::endl;
	}

	std::cin.get();
}